//
//  BusinessHoursManager.swift
//  CMB250716
//
//  Created by Assistant on 2025-01-02.
//

import Foundation

/// 营业时间管理器
struct BusinessHoursManager {
    
    // MARK: - 营业时间检查
    
    /// 检查当前时间是否在营业时间内
    static func isWithinBusinessHours(at date: Date = Date()) -> Bool {
        let calendar = Calendar.current
        let weekday = calendar.component(.weekday, from: date)
        let hour = calendar.component(.hour, from: date)
        let minute = calendar.component(.minute, from: date)
        let currentTimeInMinutes = hour * 60 + minute
        
        // 获取对应的时间段配置
        let timeSlots = isWeekend(weekday) ? AppConfig.weekendTimeSlots : AppConfig.weekdayTimeSlots
        
        // 检查是否在任一营业时间段内
        return timeSlots.contains { timeSlot in
            let startMinutes = timeStringToMinutes(timeSlot.start)
            let endMinutes = timeStringToMinutes(timeSlot.end)
            return currentTimeInMinutes >= startMinutes && currentTimeInMinutes <= endMinutes
        }
    }
    
    /// 获取下一个营业时间
    static func getNextBusinessHour(from date: Date = Date()) -> Date? {
        let calendar = Calendar.current
        var checkDate = date
        
        // 最多检查7天
        for _ in 0..<7 {
            let weekday = calendar.component(.weekday, from: checkDate)
            let timeSlots = isWeekend(weekday) ? AppConfig.weekendTimeSlots : AppConfig.weekdayTimeSlots
            
            // 检查当天是否有营业时间
            if let earliestSlot = timeSlots.min(by: { timeStringToMinutes($0.start) < timeStringToMinutes($1.start) }) {
                let startMinutes = timeStringToMinutes(earliestSlot.start)
                let currentHour = calendar.component(.hour, from: checkDate)
                let currentMinute = calendar.component(.minute, from: checkDate)
                let currentTimeInMinutes = currentHour * 60 + currentMinute
                
                // 如果是同一天且还没到营业时间
                if calendar.isDate(checkDate, inSameDayAs: date) && currentTimeInMinutes < startMinutes {
                    return calendar.date(bySettingHour: startMinutes / 60, minute: startMinutes % 60, second: 0, of: checkDate)
                }
                // 如果不是同一天，返回该天的第一个营业时间
                else if !calendar.isDate(checkDate, inSameDayAs: date) {
                    return calendar.date(bySettingHour: startMinutes / 60, minute: startMinutes % 60, second: 0, of: checkDate)
                }
            }
            
            // 检查下一天
            checkDate = calendar.date(byAdding: .day, value: 1, to: checkDate) ?? checkDate
        }
        
        return nil
    }
    
    /// 获取今天的所有营业时间段
    static func getTodayBusinessHours(for date: Date = Date()) -> [(start: String, end: String)] {
        let calendar = Calendar.current
        let weekday = calendar.component(.weekday, from: date)
        return isWeekend(weekday) ? AppConfig.weekendTimeSlots : AppConfig.weekdayTimeSlots
    }
    
    /// 获取指定日期的营业时间段（用于预订时间选择）
    static func getBusinessHoursForDate(_ date: Date) -> [(start: Date, end: Date)] {
        let calendar = Calendar.current
        let weekday = calendar.component(.weekday, from: date)
        let timeSlots = isWeekend(weekday) ? AppConfig.weekendTimeSlots : AppConfig.weekdayTimeSlots
        
        return timeSlots.compactMap { timeSlot in
            let startMinutes = timeStringToMinutes(timeSlot.start)
            let endMinutes = timeStringToMinutes(timeSlot.end)
            
            guard let startDate = calendar.date(bySettingHour: startMinutes / 60, minute: startMinutes % 60, second: 0, of: date),
                  let endDate = calendar.date(bySettingHour: endMinutes / 60, minute: endMinutes % 60, second: 0, of: date) else {
                return nil
            }
            
            return (start: startDate, end: endDate)
        }
    }
    
    // MARK: - 私有辅助方法
    
    /// 判断是否为周末
    private static func isWeekend(_ weekday: Int) -> Bool {
        return weekday == 1 || weekday == 7 // 周日=1, 周六=7
    }
    
    /// 将时间字符串转换为分钟数
    private static func timeStringToMinutes(_ timeString: String) -> Int {
        let components = timeString.split(separator: ":").compactMap { Int($0) }
        guard components.count == 2 else { return 0 }
        return components[0] * 60 + components[1]
    }
    
    /// 将分钟数转换为时间字符串
    static func minutesToTimeString(_ minutes: Int) -> String {
        let hours = minutes / 60
        let mins = minutes % 60
        return String(format: "%02d:%02d", hours, mins)
    }
}

// MARK: - 预订相关扩展
extension BusinessHoursManager {
    
    /// 获取可预订的时间选项（从明天开始的7天内）
    static func getAvailableReservationTimes() -> [Date] {
        let calendar = Calendar.current
        var availableTimes: [Date] = []
        
        // 从明天开始检查7天
        for dayOffset in 1...7 {
            guard let targetDate = calendar.date(byAdding: .day, value: dayOffset, to: Date()) else { continue }
            
            let businessHours = getBusinessHoursForDate(targetDate)
            
            // 为每个营业时间段生成30分钟间隔的时间选项
            for timeSlot in businessHours {
                var currentTime = timeSlot.start
                
                while currentTime < timeSlot.end {
                    availableTimes.append(currentTime)
                    
                    // 增加30分钟
                    guard let nextTime = calendar.date(byAdding: .minute, value: 30, to: currentTime) else { break }
                    currentTime = nextTime
                }
            }
        }
        
        return availableTimes.sorted()
    }
    
    /// 格式化预订时间显示 - 始终使用英文日期格式
    static func formatReservationTime(_ date: Date, language: String = "en") -> String {
        let formatter = DateFormatter()
        
        // 始终使用英文格式显示日期，不显示"明天"或"Tomorrow"
        formatter.locale = Locale(identifier: "en_US")
        formatter.dateFormat = "MMM dd HH:mm"
        
        return formatter.string(from: date)
    }
}